#include "CReadFile.h"

namespace ISNW
{
namespace io
{
	CReadFile::CReadFile(const c8* fname)
		:hfile(0)
		,fppos(0)
	{
		filename = fname;
		open();
	}

	CReadFile::CReadFile(const core::string& fname)
		:hfile(0)
		,fppos(0)
	{
		filename = fname;
		open();
	}

	CReadFile::~CReadFile()
	{
		if(hfile)
			CloseHandle(hfile);
		hfile = 0;
	}

	s32 CReadFile::read(void* buffer,u32 size)
	{
		if(hfile == 0) return 0;

		s32 count_read = 0;
		bool ret = ReadFile(hfile,buffer,size,(LPDWORD)&count_read,0);
		
		if(ret){
			fppos += count_read;
			return count_read;
		}

		return 0;
	}

	bool CReadFile::seek(s32 final_pos,bool relative)
	{
		if(hfile == 0) return false;

		if(final_pos == 0) return true;

		u32 move_method = FILE_BEGIN;
		if(relative) move_method = FILE_CURRENT;

		s32 ret = SetFilePointer(hfile,final_pos,0,move_method);

		if(ret == INVALID_SET_FILE_POINTER)	return false;

		fppos = ret;

		return true;
	}

	s32 CReadFile::getsize() const
	{
		if(hfile == 0) return 0;

		return GetFileSize(hfile,0);
	}

	s32 CReadFile::getpos() const
	{
		return fppos;
	}

	bool CReadFile::open()
	{
		if(filename.size())
		{
			if(hfile)
			{
				CloseHandle(hfile);
				hfile = 0;
			}
			hfile = CreateFileA(filename.c_str(),GENERIC_READ,FILE_SHARE_READ,0,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
			if(hfile == INVALID_HANDLE_VALUE)
			{
				hfile = 0;
				return false;
			}
			seek(0);
			return true;
		}
	}

	const c8* CReadFile::getfilename() const
	{
		return filename.c_str();
	}

	IReadFile* createReadFile(const c8* filename)
	{
		CReadFile* readfile = new CReadFile(filename);

		if(readfile->isopen()) return readfile;

		readfile->drop();
		return 0;
	}


} // end namespace io
} // end namespace ISNW